/****************************************************************
* Copyright (c) 2012                                            *
* author : <aspinall@oltrelinxux.com>                   	      *
* send to sms with modem GSM DIGICOM (For HotSpot)		          *
* compile gcc sms.c -lmysqlclient -Wall -o sms                  *
* Use : #./sms <id_table_on_db>                                 *
* License : This source file is under GPL                       *
* Only for Linux kernel                                         *
* Versione 1.1                                                  *
*                                                               *
*  Disclaimer:                                                  *
* Use of this information constitutes acceptance for use in     *
* an AS IS condition.There are NO warranties with regard to     *
* this information. In no event shall the author be liable for  *
* any damages whatsoever arising out of or in connection with   *
* the use or spread of this information. Any use of this        *
* information is at the user's own risk.                        *
****************************************************************/



#define _GNU_SOURCE
#include <string.h>


#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <mysql/mysql.h>
#include <time.h>

#define HOST_DB		"localhost"
#define USER_DB		"root"
#define PASS_DB		"XXXXXX"
#define NAME_DB		"hotspot"


#define QUERY_SMS       "select * from sms where id = \"%s\";"
#define AT_NUM		"AT+CMGS=\"%s\"\r\n"

#define SUC_LOG		"SUCCESS SMS SEND TO NUM: %s\n[testo] %s[/testo]\n"
#define ERR_LOG		"ERROR   SMS SEND TO NUM: %s\n[testo] %s[/testo]\n"

#define MODEM		"/dev/ttyS0"
#define LOG		"/var/www/exec/log.txt"

#define LEN_SMS         160 
#define LEN_LOG		1024
#define LEN_CELL	12


void help(void){
	printf("Use: ./sms [id table sms]\n");
	exit(EXIT_FAILURE);
}


int main(int argc,char** argv){

        struct termios tio;
        int tty_fd;
        size_t querylen;
	size_t at_num_len;
        char *query = NULL;
	char *at1 = "AT+CMGF=1\r\n"; 
	char *at2 = NULL;
	char stop[] = {0x1A, 0x00}; /* ctrl +z */
	char buffer[100]; 
	char buf_log[LEN_LOG];
	char success=0;

	FILE  *fp;
        MYSQL *conn;
        MYSQL_RES *result;
        MYSQL_ROW row=NULL;
        char text_sms[LEN_SMS];
        int num_rows;

        time_t t1,t2;
        (void) time(&t1);

	if(argc != 2)
		help();

	if(getuid() != 0){
		printf("Non sei utente root!\n");
		exit(EXIT_FAILURE);
	}

	memset(buf_log, 0x00, LEN_LOG);
        memset(text_sms, 0x00, LEN_SMS);
	at_num_len = strlen(AT_NUM) + LEN_CELL;
	at2 = calloc(1, at_num_len);
	querylen = strlen(QUERY_SMS)+ strlen(argv[1] + 0x1);
        query = calloc(1, querylen);
        snprintf(query, querylen, QUERY_SMS, argv[1]);

	fp = fopen(LOG, "a+");
	if( fp == NULL ){
		perror("Errore in apertura del file");
		exit(EXIT_FAILURE);
	}

        conn = mysql_init(NULL);

        if (conn == NULL) {
                printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
                exit(1);
        }

        if (mysql_real_connect(conn, HOST_DB, USER_DB, PASS_DB, NAME_DB, 0, NULL, 0) == NULL) {
                printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
                exit(1);
        }

	if (mysql_query(conn, query)) {
                printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
                exit(1);
        }

        result = mysql_store_result(conn);
        num_rows = mysql_num_rows(result);

	if(num_rows!=1){
		printf("Id mancante o database compromesso\n");
		exit(EXIT_FAILURE);
	}

        row = mysql_fetch_row(result);
	
	        snprintf(at2, at_num_len, AT_NUM, row[1]);
                memcpy(text_sms, row[3], LEN_SMS);


        memset(&tio,0,sizeof(tio));
	memset(buffer, 0x00, 100);
        tio.c_iflag=0;
        tio.c_oflag=0;
        tio.c_cflag=CS8|CREAD|CLOCAL;
        tio.c_lflag=0;
        tio.c_cc[VMIN]=1;
        tio.c_cc[VTIME]=5;
 
        tty_fd=open(MODEM, O_RDWR | O_NONBLOCK);      
        cfsetospeed(&tio,B9600);
        cfsetispeed(&tio,B9600);
 
        tcsetattr(tty_fd,TCSANOW,&tio);


		/* send data Serial */
		write(tty_fd,at1,strlen(at1));
		usleep(300000);
                write(tty_fd,at2,strlen(at2));
		usleep(300000);
                write(tty_fd,text_sms,strlen(text_sms));
                write(tty_fd,stop,2);

		while(memmem(buffer, 100, "+CMGS:", 6) == NULL){
			read(tty_fd, buffer, 100);
		        (void) time(&t2);
			
			if(t2-t1 > 10){
				snprintf(buf_log, strlen(ERR_LOG) + strlen(row[1]) + strlen(row[3]) + 0x4, ERR_LOG, row[1], row[3]);     
				fputs(buf_log, fp);
				success = 1;
				break;
			}
		}

		write(tty_fd, "ATH\r\n", 5);
		/**/


	/* LOG SUCCESS */
	if(!success){
		snprintf(buf_log, strlen(SUC_LOG) + strlen(row[1]) + strlen(row[3]) + 0x4, SUC_LOG, row[1], row[3]);	
		fputs(buf_log, fp);
	}
	/**/

        close(tty_fd);
	free(query);
	free(at2);
	mysql_free_result(result);
	mysql_close(conn);
        fclose(fp);


return 0;
}